package cn.ctyun.xstore.s3.controller;

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.PartETag;

import cn.ctyun.xstore.s3.Conf;
import cn.ctyun.xstore.s3.api.object.GeneratePresignedUrl;
import cn.ctyun.xstore.s3.api.object.MultipleUpload;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/s3")
public class S3DemoController {

    @Autowired
    private AmazonS3 s3;


    @PostMapping(value = "/initUpload")
    public Map<String, Object> initUpload(String fileName, int partCount) {
        Map<String, Object> result = new HashMap<>();
        String uploadId = MultipleUpload.init(Conf.DEFAULT_BUCKET, fileName, s3);
        result.put("uploadId", uploadId);
        result.put("uploadUrls", MultipleUpload.getUploadPartUrls(Conf.DEFAULT_BUCKET, fileName, uploadId, partCount, s3));

        return result;
    }

    @PostMapping(value = "/completeUpload")
    public void completeUpload(String fileName, String uploadId, int partCount, HttpServletRequest request) {
        List<PartETag> eTags = new ArrayList<>(partCount);
        for (int i = 1; i <= partCount; i++) {
            String eTag = request.getParameter("eTag-" + i);
            eTags.add(new PartETag(i, eTag));
        }
        MultipleUpload.complete(Conf.DEFAULT_BUCKET, fileName, uploadId, eTags, s3);
    }

    @PostMapping(value = "/abortUpload")
    public void abortUpload(String fileName, String uploadId) {
        MultipleUpload.abort(Conf.DEFAULT_BUCKET, fileName, uploadId, s3);
    }
}
